package com.hhf.riceshopping.order.interceptor;

import com.hhf.common.constant.AuthServerConstant;
import com.hhf.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登陆的拦截器
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    //为了让其他功能的线程都能访问到登陆后的用户信息并可以取出登陆的用户，就可以共享登陆后用户数据用ThreadLocal
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<MemberRespVo>();
    /**
     * 目标请求到达之前来做前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //直接放行
        //  /order/order/status/2948294820984028420
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/order/order/status/**", uri);
        boolean match1 = antPathMatcher.match("/payed/notify", uri);
        if(match || match1){
            return true;
        }


        //获取登陆的用户
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute!=null){
            //说明登陆了，就放行
            loginUser.set(attribute);//登陆的用户
            return true;
        }else {
            //没登陆就提示登陆
            request.getSession().setAttribute("msg","请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }

    }
}
